import { dbTable, component, oss } from "d8d-block";
import { env } from "d8d-design-cloud";

const getSysInfoMap = async (配置名称: string) => {
  const { dbQuery } = dbTable.knex("sysconfig_info", false);
  dbQuery.column("配置值");
  dbQuery.where("配置名称", 配置名称);
  const resQuery = await dbQuery.first();
  if (resQuery) {
    const infos = resQuery?.配置值?.split("\n") ?? [];
    return new Map(
      infos?.map((item) => {
        const arr = item.split(":");
        return [Number(arr[0]), arr[1]];
      })
    );
  }
};

const handleArr = async (arr:any[],name:string) => {
    const sysMap = await getSysInfoMap(name)
    return arr.map(item => {
        return {
            ...item,
            [name]: sysMap?.get(item[name]) ?? item[name]
        }
    })
};

export default async (ctx) => {
  try {
    var 图表数据_5RW4yS328a = [];
    const query = dbTable.query("zichan_info", ctx.querystring, false);
    // console.log(query)
    query.column([
      "设备状态",
      // "入库数量",
    ]);
    query.whereNotNull("IP地址");
    query.groupBy("设备状态");
    query.count("_id", { as: "设备数" });
    图表数据_5RW4yS328a = await query;

    const arr = await handleArr(图表数据_5RW4yS328a,'设备状态')

    ctx.body = {
      code: 200,
      message: "ok",
      data: arr,
    };
  } catch (error) {
    ctx.body = {
      code: 500,
      message: "Internal Server Error",
      error: error.message,
    };
  }
};
